<template>
  <div class="page gray-page inspect-page">
    <nav-bar :title="title" border></nav-bar>
    <div class="page-main" style="margin-top: 44px">
      <inspect-head v-model="gridCode" type="company" @change="handleChange"></inspect-head>
      <div class="inspect-map" id="container"></div>
    </div>
  </div>
</template>
<script>
import InspectHead from '@/components/Widget/InspectVisit/Inspect/head'
import InspectVisit from '@/api/inspectVisit'
import { formatTimes } from '@/libs/tool'
import mapPlugin from '@/libs/mapPlugin'
// 定义一些常量
var PI = 3.1415926535897932384626
var a = 6378245.0
var ee = 0.00669342162296594323
export default {
  components: { InspectHead },
  data() {
    return {
      title: '重点单位巡查',
      gridCode: '',
      inspectPoint: [],

      // 地图
      map: null,
      center: [],
      markers: [],
      overlayGroup: null
    }
  },
  created() {
    this.gridCode = this.$route.query.gridCode
  },
  mounted() {
    this.map = new AMap.Map('container', {
      resizeEnable: true,
      zoom: 16
    })
  },
  methods: {
    /**
     * WGS84转GCj02
     * @param lng
     * @param lat
     * @returns {*[]}
     */
    wgs84togcj02(lng, lat) {
      if (this.out_of_china(lng, lat)) {
        return [lng, lat]
      } else {
        var dlat = this.transformlat(lng - 105.0, lat - 35.0)
        var dlng = this.transformlng(lng - 105.0, lat - 35.0)
        var radlat = (lat / 180.0) * PI
        var magic = Math.sin(radlat)
        magic = 1 - ee * magic * magic
        var sqrtmagic = Math.sqrt(magic)
        dlat = (dlat * 180.0) / (((a * (1 - ee)) / (magic * sqrtmagic)) * PI)
        dlng = (dlng * 180.0) / ((a / sqrtmagic) * Math.cos(radlat) * PI)
        var mglat = lat + dlat
        var mglng = lng + dlng
        return [mglng, mglat]
      }
    },

    getInspect() {
      InspectVisit.Company.list({
        gridCode: this.gridCode,
        date: this.$route.query.date || formatTimes.formatDate(new Date())
      }).then(res => {
        const { status, data } = res.data
        if (status === 0) {
          this.inspectPoint = data.gridInspectionPoint
          this.inspectPoint.length && this.setMarker()
        }
      })
    },
    // 切换网格
    handleChange(v, item) {
      // 设置中心点
      this.center = [item.longitude, item.latitude]
      this.map.setCenter(this.center)
      this.map.setZoom(16)
      if (this.overlayGroup) {
        this.map.remove(this.overlayGroup)
        this.overlayGroup = null
        this.markers = []
      }
      this.getInspect()
    },
    // marker
    async setMarker() {
      for (const item of this.inspectPoint) {
        // 巡查状态
        let lastStatus = 'inspect'
        // let statusStr = ''
        if (item.inspectionPointRecord.length) {
          // 最后一条巡查点状态
          const last = item.inspectionPointRecord[item.inspectionPointRecord.length - 1]
          lastStatus =
            (last.latentDangerResult && last.latentDangerResult === '0') ||
            (!last.latentDangerResult && last.inspectionResult === '1')
              ? 'abnormal'
              : 'normal'
        }

        // marker
        const img = require(`@/assets/images/inspectVisit/inspect/icon_map_${lastStatus}@2x.png`)
        const content = `
        <div class="amap-marker-inspect-content">
            <img src="${img}" width="32px" alt="">
            <div class="${lastStatus}">
              ${item.companyName}
              <i class="van-icon van-icon-${lastStatus === 'abnormal' ? 'warning' : ''}"></i>
            </div>
        </div>`
        const data = await this.wgs84togcj02(item.longitude, item.latitude)
        const marker = new AMap.Marker({
          position: new AMap.LngLat(data[0].toFixed(8), data[1].toFixed(8)),
          content: content,
          anchor: 'bottom-center'
        })
        this.markers.push(marker)

        // 点击
        marker.on('click', () => {
          if (item.inspectionPointRecord.length) {
            // 已巡查
            this.$router.push({
              path: '/inspectvisit/inspect/company/detail',
              query: {
                gridCode: this.gridCode,
                inspectionPointCode: item.companyCode,
                date: this.$route.query.date
              }
            })
          } else {
            // 未巡查
            mapPlugin.geolocation(result => {
              const lnglat1 = result.position
              const lnglat2 = [item.longitude, item.latitude]
              const distance = lnglat1.distance(lnglat2)
              if (distance <= 100) {
                this.$router.push({
                  path: '/inspectvisit/inspect/company/report',
                  query: {
                    gridCode: this.gridCode,
                    inspectionPointCode: item.companyCode
                  }
                })
              } else {
                this.$toast({
                  message: '距离当前巡查点过远，请重试',
                  position: 'bottom'
                })
              }
            })
          }
        })
      }
      if (this.markers.length) {
        this.overlayGroup = new AMap.OverlayGroup(this.markers)
        this.map.add(this.overlayGroup)
      }
    },
    transformlat(lng, lat) {
      var ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng))
      ret += ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0) / 3.0
      ret += ((20.0 * Math.sin(lat * PI) + 40.0 * Math.sin((lat / 3.0) * PI)) * 2.0) / 3.0
      ret += ((160.0 * Math.sin((lat / 12.0) * PI) + 320 * Math.sin((lat * PI) / 30.0)) * 2.0) / 3.0
      return ret
    },
    transformlng(lng, lat) {
      var ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng))
      ret += ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0) / 3.0
      ret += ((20.0 * Math.sin(lng * PI) + 40.0 * Math.sin((lng / 3.0) * PI)) * 2.0) / 3.0
      ret += ((150.0 * Math.sin((lng / 12.0) * PI) + 300.0 * Math.sin((lng / 30.0) * PI)) * 2.0) / 3.0
      return ret
    },
    /**
     * 判断是否在国内，不在国内则不做偏移
     * @param lng
     * @param lat
     * @returns {boolean}
     */
    out_of_china(lng, lat) {
      return lng < 72.004 || lng > 137.8347 || lat < 0.8293 || lat > 55.8271 || false
    }
  }
}
</script>
<style scoped lang="less">
@import '~@/assets/style/inspectVisit/inspect/index.less';
</style>
